package com.hdoit.kylin.web.document.controllers;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tennetcn.common.enums.ManageContainer;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.enums.pub.YesOrNoInteger;
import com.tennetcn.common.logical.file.model.FileCatalog;
import com.tennetcn.common.logical.file.service.IFileCatalogService;
import com.tennetcn.common.logical.viewmodel.file.FileCatalogSearch;
import com.tennetcn.common.selfcommon.enums.file.CatalogType;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.Configuration;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.common.utils.QRCodeUtils;
import com.tennetcn.component.web.ActionResult;
import com.tennetcn.component.web.BaseController;
import com.tennetcn.component.web.ErrorResult;
import com.tennetcn.component.web.JsonActionResult;
import com.tennetcn.plugins.devshorts.enumerable.Enumerable;

/**
 * @author      chenghuan
 * @email       
 * @createtime  2017年06月23日 14:22:51
 * @comment
 */
@Controller
@RequestMapping(value = "/admin/document/fileCatalog/")
public class MyFileCatalogController extends BaseController{
    @Override
    public String getRoutePath() {
        return "areas/admin/document/fileCatalog/";
    }

    private IFileCatalogService fileCatalogService;
    public IFileCatalogService getFileCatalogService() {
        return fileCatalogService;
    }
    @Resource
    public void setFileCatalogService(IFileCatalogService fileCatalogService) {
        this.fileCatalogService = fileCatalogService;
    }

    private final String indexViewName="index";
    private final String outputViewName="output";
    private final String detailedViewName="fileCatalogDetailed";
    private final String saveViewName="save";
    private final String deleteViewName = "delete";
    private final String newFolderViewName="newFolder";
    private final String qrCodeViewName="qrCode";

    @RequestMapping(value = indexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String index(Model model){

        return view(indexViewName);
    }
    
    @RequestMapping(value = outputViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String output(Model model,FileCatalogSearch search){
    	
    	search.setCreateUserId(getLoginModel().getLoginId());
        List<FileCatalog> catalogs= fileCatalogService.queryList(search);

        List<FileCatalog> folderCatalogs =Enumerable.init(catalogs).filter(fc->CatalogType.folder.equals(fc.getCatalogType())).toList();
        List<FileCatalog> fileCatalogs =Enumerable.init(catalogs).filter(fc->CatalogType.file.equals(fc.getCatalogType())).toList();
        
        model.addAttribute("folderCatalogs", folderCatalogs);
        model.addAttribute("fileCatalogs", fileCatalogs);
        
        return view(outputViewName);
    }

    @RequestMapping(value = detailedViewName, method = { RequestMethod.GET})
    public String fileCatalogDetailed(Model model,String key){
        FileCatalog fileCatalog=new FileCatalog();
        if(!StringUtils.isEmpty(key)){
            fileCatalog=fileCatalogService.queryModel(key);
        }
        model.addAttribute("fileCatalog", fileCatalog);
        return view(detailedViewName);
    }

    @RequestMapping(value = saveViewName, method = { RequestMethod.POST})
    public String save(Model model,FileCatalog fileCatalog){
        if(StringUtils.isEmpty(fileCatalog.getId())){
            fileCatalog.setId(CommonUtils.getKeyId());
            fileCatalog.setCreateDate(DateUtils.getCurrent());
            fileCatalog.setDeleteMark(YesOrNoInteger.no);
            fileCatalog.setCreateUserId(getLoginModel().getLoginId());
            fileCatalog.setCreateUserName(getLoginModel().getLoginName());
            fileCatalog.setModelStatus(ModelStatus.add);
        }else{
            fileCatalog.setModifyDate(DateUtils.getCurrent());
            fileCatalog.setModifyUserId(getLoginModel().getLoginId());
            fileCatalog.setModifyUserName(getLoginModel().getLoginName());
            fileCatalog.setModelStatus(ModelStatus.update);
        }

        ActionResult actionResult;
        if(fileCatalogService.applyChange(fileCatalog)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("fileCatalog", fileCatalog);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(detailedViewName);
    }

    @RequestMapping(value =deleteViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String delete(String key){
        if(fileCatalogService.deleteFakeByKey(key)){
            return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }
        return new JsonActionResult(ManageContainer.ERROR).toJson();
    }
    
    @ResponseBody
    @RequestMapping(value =newFolderViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public String newFolder(String folderName,String parentId,int parentLevel){
       FileCatalog fileCatalog=new FileCatalog();
       fileCatalog.setCatalogType(CatalogType.folder);
       fileCatalog.setShowName(folderName);
       fileCatalog.setStorageName(folderName);
       fileCatalog.setParentId(parentId);
       fileCatalog.setCreateDate(DateUtils.getCurrent());
       fileCatalog.setCreateUserId(getLoginModel().getLoginId());
       fileCatalog.setCreateUserName(getLoginModel().getLoginName());
       fileCatalog.setDeleteMark(YesOrNoInteger.no);
       fileCatalog.setLevel(parentLevel+1);
       fileCatalog.setId(CommonUtils.getKeyId());
       
       if(fileCatalogService.addModelSelective(fileCatalog)){
    	   return new JsonActionResult(ManageContainer.SUCCESS).toJson();
       }else{
    	   return new JsonActionResult(ManageContainer.ERROR).toJson();
       }
    }
    
    @RequestMapping(value = qrCodeViewName, method = { RequestMethod.GET,RequestMethod.POST })
	public void qrCode(Model model,String fileId,HttpServletRequest request,HttpServletResponse response) {		
		String logoPath=request.getServletContext().getRealPath("/WEB-INF/content/images/dysmall.png");

		String qrCodeContent=Configuration.getInstance().getValue("conf.curr.http.prefix")+"/admin/download/file?catalogId="+fileId;
		
		BufferedImage bufferedImage=QRCodeUtils.getQR_CODEBufferedImage(qrCodeContent);
		
		File file=new File(logoPath);
		if(file.isFile()){
			QRCodeUtils.addLogo_QRCode(bufferedImage, file);
		}
		
		response.setContentType("image/png");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
		
		try {
			ImageIO.write(bufferedImage, "png", response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}